package ferri.lorenzo;

import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

//Create list 
public class AlbumListAdapter extends SimpleCursorAdapter {
	static final String TAG = "[AlbumListAdapter]";

	static class ViewHolder {
		ImageView artwork;
		TextView album;
		TextView artist;
	}
	
	public AlbumListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
		super(context, layout, c, from, to);
	}
	
	//Create albumList style
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		
		View v = super.newView(context, cursor, parent); 

		ViewHolder vh = new ViewHolder();
		vh.album = (TextView)v.findViewById(R.id.text_album);
		vh.artist = (TextView)v.findViewById(R.id.text_artist);
		vh.artwork = (ImageView)v.findViewById(R.id.icon);
		
		v.setTag(vh);
		
		return v;
	}
	
	//Set value of the view component 
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		
		ViewHolder vh = (ViewHolder)view.getTag();
		
	
		String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
		vh.album.setText(album);
		

		String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
		vh.artist.setText(artist);
		
		//Repository of albumarts URI
    	Uri baseUri = Uri.parse("content://media/external/audio/albumart");
		
    	//ID Album
    	long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
		
		//Albumart URI
		Uri artworkUri = ContentUris.withAppendedId(baseUri, albumId);
		
		//Find the albumart at set the value of the ImageView artwork
		if (artworkUri != null) {
			ParcelFileDescriptor fd = null;
			try {
		    	ContentResolver cr = context.getContentResolver();
				fd = cr.openFileDescriptor(artworkUri, "r");
				Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
				vh.artwork.setImageBitmap(b);
			} catch (FileNotFoundException e) {
				vh.artwork.setImageResource(R.drawable.albumart_mp_unknown);
            } finally {
                try {
                    if (fd != null) {
                        fd.close();
                    }
                } catch (IOException e) {
                }
            }
		}
	}
}